package cn.itcast.mq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {
    // 声明队列
    @Bean
    public Queue testQueue() {
        return new Queue("test.queue", true);  // 持久化队列‌:ml-citation{ref="1,6" data="citationList"}
    }

    // 声明Topic交换机（使用RabbitMQ默认的amq.topic）
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange("amq.topic");  // 使用系统预定义交换机‌:ml-citation{ref="2,6" data="citationList"}
    }

    // 绑定队列到交换机
    @Bean
    public Binding topicBinding() {
        return BindingBuilder.bind(testQueue())
                .to(topicExchange())
                .with("a.simple.test");  // 路由键匹配规则‌:ml-citation{ref="2,8" data="citationList"}
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取RabbitTemplate对象
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 配置ReturnCallback
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            // 判断是否是延迟消息
            Integer receivedDelay = message.getMessageProperties().getReceivedDelay();
            if (receivedDelay != null && receivedDelay > 0) {
                // 是一个延迟消息，忽略这个错误提示
                return;
            }
            // 记录日志
            log.error("消息发送到队列失败，响应码：{}, 失败原因：{}, 交换机: {}, 路由key：{}, 消息: {}",
                     replyCode, replyText, exchange, routingKey, message.toString());
            // 如果有需要的话，重发消息
        });
    }


}
